<script setup lang="ts">
import { onMounted } from 'vue';
import { useBroadcast, useOAuth } from '../../composables';
import { isMobileTerminal } from '@/utils';

const broadcast = useBroadcast();
const { oauthLogin } = useOAuth();

onMounted(() => {
  // 用户扫码在手机点击确认之后的回调, 且存在缓存
  (window as unknown as any)?.QC?.Login(
    {
      btnId: 'qqLoginBtn'
    },
    (data: any, opts: any) => {
      console.log(data, opts);
      // 注销登录, 清除缓存
      (window as unknown as any)?.QC?.Login.signOut();

      const accessToken = /access_token=((.*))&expires_in/.exec(
        window.location.hash
      )?.[1];

      const oauthObj = {
        nickname: data.nickname,
        figureurl_qq_2: data.figureurl_qq_2,
        accessToken
      };

      broadcast.send(oauthObj);

      // 移动端没有窗口的概念, 无需跨窗口传参, 直接登录
      if (isMobileTerminal) {
        oauthLogin('QQ', oauthObj);
      }

      window.close();
    }
  );
});

const onQQLogin = () => {
  openQQWindow();
};

const openQQWindow = () => {
  const url =
    `https://graph.qq.com/oauth2.0/authorize?client_id=101998494` +
    `&redirect_uri=https%3A%2F%2Fimooc-front.ldgsunday.club%2Flogin` +
    `&response_type=token` +
    `&scope=all`;
  window.open(
    url,
    'oauth2Login_10699',
    'height=525,width=585,toolbar=no,menubar=no,location=no,status=no,location=yes,resizable=yes'
  );
  broadcast.wait().then(oauthObj => {
    broadcast.clear();

    oauthLogin('QQ', oauthObj);
  });
};
</script>

<template>
  <div>
    <span id="qqLoginBtn" v-show="false" />
    <MSvgIcon name="qq" class="w-4 cursor-pointer" @click="onQQLogin" />
  </div>
</template>
